//
//  videoDistanceViewController.m
//  FaceTest
//
//  Created by chabao on 2018/4/11.
//

#import "photoAlbumViewController.h"
#import "photoAlbumViewController.h"

#import "ICGVideoTrimmerView.h"
#import <Photos/PHPhotoLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface photoAlbumViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, ICGVideoTrimmerDelegate>

@property (strong, nonatomic)  ICGVideoTrimmerView *trimmerView;
@property (strong, nonatomic)  UIButton *trimButton;
@property (strong, nonatomic)  UIView *videoLayer;

@property (assign, nonatomic) BOOL isPlaying;
@property (strong, nonatomic) AVPlayer *player;
@property (strong, nonatomic) AVPlayerItem *playerItem;
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
@property (strong, nonatomic) NSTimer *playbackTimeCheckerTimer;
@property (assign, nonatomic) CGFloat videoPlaybackPosition;

@property (strong, nonatomic) NSString *tempVideoPath;
@property (strong, nonatomic) AVAssetExportSession *exportSession;
@property (strong, nonatomic) AVAsset *asset;

@property (assign, nonatomic) CGFloat startTime;
@property (assign, nonatomic) CGFloat stopTime;

@property (assign, nonatomic) BOOL restartOnPlay;

@end

@implementation photoAlbumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tempVideoPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmpMov.mov"];
    [self openVideoLibrary];
}

-(void)loadViews:(AVAsset *)asset {
    
    UIButton *leftbutton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 20)];
    [self set:leftbutton withStr:@"取消添加"];
    [leftbutton addTarget:self action:@selector(cancle) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:leftbutton];
    
    self.navigationItem.leftBarButtonItem=leftBarButtonItem;
    
    float Y = SCREEN_HEIGHT * 0.9;
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.08, Y, 80, 30)];
    [cancelBtn setBackgroundColor:[UIColor colorWithRed:0.9 green:0.9 blue:1 alpha:0.5]];
    cancelBtn.layer.cornerRadius = 5;
    [self set:cancelBtn withStr:@"重新选择"];
    [cancelBtn addTarget:self action:@selector(openVideoLibrary) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *doneBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.37, Y, 100, 30)];
    [doneBtn setBackgroundColor:[UIColor colorWithRed:0.9 green:0.9 blue:1 alpha:0.5]];
    doneBtn.layer.cornerRadius = 5;
    [self set:doneBtn withStr:@"添加并保存"];
    [doneBtn addTarget:self action:@selector(addAndSaveVedio) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.7, Y, 80, 30)];
    [addBtn setBackgroundColor:[UIColor colorWithRed:0.9 green:0.9 blue:1 alpha:0.5]];
    addBtn.layer.cornerRadius = 5;
    [self set:addBtn withStr:@"添加"];
    [addBtn addTarget:self action:@selector(addVedio) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *videoLayer = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT * 0.15, SCREEN_WIDTH, SCREEN_HEIGHT * 0.54)];
    self.videoLayer = videoLayer;
    
    ICGVideoTrimmerView *trimmerView = [[ICGVideoTrimmerView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT * 0.7, SCREEN_WIDTH, SCREEN_HEIGHT * 0.15) asset:asset];
    trimmerView.backgroundColor = [UIColor yellowColor];
    self.trimmerView = trimmerView;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view addSubview:cancelBtn];
        [self.view addSubview:doneBtn];
        [self.view addSubview:addBtn];
        [self.view addSubview:self.videoLayer];
        [self.view addSubview:self.trimmerView];
    });
}

// 放弃添加视频
- (void)cancle {
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 添加并保存
- (void)addAndSaveVedio {
    [self addAndSaveVedio:true];
}

// 添加
- (void) addVedio {
    [self addAndSaveVedio:false];
}

// 添加或者保存视频的方法
- (void)addAndSaveVedio: (bool )flag {
    [self tapOnVideoLayer:nil];
    [self deleteTempFile];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:self.asset];
    if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
        self.exportSession = [[AVAssetExportSession alloc]
                              initWithAsset:self.asset presetName:AVAssetExportPresetPassthrough];
        NSURL *furl = [NSURL fileURLWithPath:self.tempVideoPath];
        self.exportSession.outputURL = furl;
        self.exportSession.outputFileType = AVFileTypeMPEG4;
        CMTime start = CMTimeMakeWithSeconds(self.startTime, self.asset.duration.timescale);
        CMTime duration = CMTimeMakeWithSeconds(self.stopTime - self.startTime, self.asset.duration.timescale);
        CMTimeRange range = CMTimeRangeMake(start, duration);
        self.exportSession.timeRange = range;
        [self.exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([self.exportSession status]) {
                case AVAssetExportSessionStatusFailed:
                NSLog(@"Export failed: %@", [[self.exportSession error] localizedDescription]);
                break;
                case AVAssetExportSessionStatusCancelled:
                NSLog(@"Export canceled");
                break;
                default:
                NSLog(@"NONE");
                NSURL *movieUrl = [NSURL fileURLWithPath:self.tempVideoPath];
                [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                    if (status == PHAuthorizationStatusNotDetermined || status == PHAuthorizationStatusAuthorized) {
                        NSLog(@"尝试保存");
                        [self sendTheBase64StrWithURLWithPath:self.tempVideoPath];
                        if (flag) {UISaveVideoAtPathToSavedPhotosAlbum([movieUrl relativePath], self,@selector(video:didFinishSavingWithError:contextInfo:), nil);}
                        else {NSLog(@"没有保存, 地址是: %@", movieUrl);}
                    } else {NSLog(@"保存失败, 地址是: %@", movieUrl);}
                }];
                break;
            }
        }];
    }
    [self stopPlaybackTimeChecker];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)sendTheBase64StrWithURLWithPath: (NSString *)filePath {
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSString *_encodedImageStr =  [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSLog(@"转化的: %@", _encodedImageStr);
    NSString *encodingImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSLog(@"%@", encodingImageStr);
    if (self.photoAlbumCallBackBlcok) {
        self.photoAlbumCallBackBlcok(encodingImageStr);
    }
    [self cancle];

}

- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error == nil) {
        NSLog(@"保存成功") ;
        NSLog(@"%@", videoPath);
    }
        else{NSLog(@"保存失败") ;}
}



//  富文本的形式设置按钮的样式和文字, 不然按钮的文字会带有下划线
-(void)set:(UIButton *)button withStr: (NSString *)str {
    NSMutableAttributedString* tncString = [[NSMutableAttributedString alloc] initWithString:str];
    [tncString addAttribute:NSUnderlineStyleAttributeName
                      value:@(NSUnderlineStyleNone)
                      range:(NSRange){0,[tncString length]}];
    
    [button setAttributedTitle:tncString forState:UIControlStateNormal];
}

//  打开相册中的视频
- (void)openVideoLibrary{
    [self tapOnVideoLayer:nil];
    //打开控制器
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    //设置媒体类型
    picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;//打开相册库,用户与电脑同步的,不能删除
    picker.delegate =self;
    picker.allowsEditing =NO;

    picker.mediaTypes = @[(NSString *)kUTTypeMovie, (NSString *)kUTTypeImage];
    //显示控制器
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - ICGVideoTrimmerDelegate
- (void)trimmerView:(ICGVideoTrimmerView *)trimmerView didChangeLeftPosition:(CGFloat)startTime rightPosition:(CGFloat)endTime
{
    _restartOnPlay = YES;
    [self.player pause];
    self.isPlaying = NO;
    [self stopPlaybackTimeChecker];
    
    [self.trimmerView hideTracker:true];
    
    if (startTime != self.startTime) {
        //then it moved the left position, we should rearrange the bar
        [self seekVideoToPos:startTime];
    }
    else{ // right has changed
        [self seekVideoToPos:endTime];
    }
    self.startTime = startTime;
    self.stopTime = endTime;
    
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:NO completion:nil];
    [self cancle];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]) { // 从相册中选的是图片
        NSURL *url = nil;
        if (@available(iOS 11.0, *)) {
             url = [info objectForKey:UIImagePickerControllerImageURL];

        } else {
            url = [info objectForKey: UIImagePickerControllerOriginalImage];
        }
        UIImage *image = [UIImage imageWithContentsOfFile:[url path]];
        NSData *data = UIImageJPEGRepresentation(image, 1.0f);
        NSString *encodingImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

        if (self.photoAlbumCallBackBlcok) {
            self.photoAlbumCallBackBlcok(encodingImageStr);
        }
        [self cancle];
    } else if ([mediaType isEqualToString:@"public.movie"]) { // 从相册中选的是视频
        
        NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];
        self.asset = [AVAsset assetWithURL:url];
        [self loadViews:self.asset];
        AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:self.asset];
        
        self.player = [AVPlayer playerWithPlayerItem:item];
        self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        self.playerLayer.contentsGravity = AVLayerVideoGravityResizeAspect;
        self.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
        
        [self.videoLayer.layer addSublayer:self.playerLayer];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnVideoLayer:)];
        [self.videoLayer addGestureRecognizer:tap];
        
        self.videoPlaybackPosition = 0;
        
        [self tapOnVideoLayer:tap];
        
        // set properties for trimmer view
        [self.trimmerView setThemeColor:[UIColor lightGrayColor]];
        [self.trimmerView setAsset:self.asset];
        [self.trimmerView setShowsRulerView:YES];
        [self.trimmerView setRulerLabelInterval:10];
        [self.trimmerView setTrackerColor:[UIColor cyanColor]];
        [self.trimmerView setDelegate:self];
        
        // important: reset subviews
        [self.trimmerView resetSubviews];
        
    }
 
    //    [self.trimButton setHidden:NO];
    
}

// 播放剪切后的视频或者暂停视频的播放
- (void)tapOnVideoLayer:(UITapGestureRecognizer *)tap
{
    if (self.isPlaying) {
        [self.player pause];
        [self stopPlaybackTimeChecker];
    }else {
        if (_restartOnPlay){
            [self seekVideoToPos: self.startTime];
            [self.trimmerView seekToTime:self.startTime];
            _restartOnPlay = NO;
        }
        [self.player play];
        [self startPlaybackTimeChecker];
    }
    self.isPlaying = !self.isPlaying;
    [self.trimmerView hideTracker:!self.isPlaying];
}

- (void)startPlaybackTimeChecker
{
    [self stopPlaybackTimeChecker];
    
    self.playbackTimeCheckerTimer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(onPlaybackTimeCheckerTimer) userInfo:nil repeats:YES];
}

- (void)seekVideoToPos:(CGFloat)pos
{
    self.videoPlaybackPosition = pos;
    CMTime time = CMTimeMakeWithSeconds(self.videoPlaybackPosition, self.player.currentTime.timescale);
    //NSLog(@"seekVideoToPos time:%.2f", CMTimeGetSeconds(time));
    [self.player seekToTime:time toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
}

- (void)stopPlaybackTimeChecker
{
    if (self.playbackTimeCheckerTimer) {
        [self.playbackTimeCheckerTimer invalidate];
        self.playbackTimeCheckerTimer = nil;
    }
}

- (void)dismissViewController {
    for (UIViewController * VC in self.navigationController.viewControllers) {
        NSLog(@"%@", VC);
        [VC dismissViewControllerAnimated:YES completion:nil];
    }
}


#pragma mark - PlaybackTimeCheckerTimer
- (void)onPlaybackTimeCheckerTimer
{
    CMTime curTime = [self.player currentTime];
    Float64 seconds = CMTimeGetSeconds(curTime);
    if (seconds < 0){
        seconds = 0; // this happens! dont know why.
    }
    self.videoPlaybackPosition = seconds;
    
    [self.trimmerView seekToTime:seconds];
    
    if (self.videoPlaybackPosition >= self.stopTime) {
        self.videoPlaybackPosition = self.startTime;
        [self seekVideoToPos: self.startTime];
        [self.trimmerView seekToTime:self.startTime];
    }
}


#pragma mark - Actions
// 删除压缩后的缓存视频,不删除的话会保存不了
- (void)deleteTempFile
{
    NSURL *url = [NSURL fileURLWithPath:self.tempVideoPath];
    NSFileManager *fm = [NSFileManager defaultManager];
    BOOL exist = [fm fileExistsAtPath:url.path];
    NSError *err;
    if (exist) {
        [fm removeItemAtURL:url error:&err];
        NSLog(@"file deleted");
        if (err) {
            NSLog(@"file remove error, %@", err.localizedDescription );
        }
    } else {
        NSLog(@"no file by that name");
    }
}

#pragma mark - PlaybackTimeCheckerTimer
- (void)viewDidLayoutSubviews
{
    self.playerLayer.frame = CGRectMake(0, 0, self.videoLayer.frame.size.width, self.videoLayer.frame.size.height);
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSThread currentThread] cancel];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

